//
//  YZMStockViewController.m
//  YZMicroStock
//
//  Created by wangminhong on 16/3/24.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMStockViewController.h"
#import "YZMSegmentViewFixed.h"
#import "YZMStockInfoView.h"
#import "YZMControllerManager.h"
#import "YZMStockEntrustView.h"
#import "YZMStockSellView.h"
#import "YZMStockSettlementView.h"
#import "YZMWebViewService.h"
#import "YZClient.h"
#import "YZMMyStackModel.h"
#import "YZMMarketValueModel.h"
#import "NSNumber+Utils.h"
#import "YZMConfigureService.h"
#import "YZMSaleTradeModel.h"
#import "YZMAlertView.h"
#import "YZMSeverTimeService.h"
#import "YZMMYTackViewController.h"
#import "YZMAppDelegate.h"
#import "MTGuideImageView.h"


NSString *const sYZDShowImageFlagDefault = @"YZDShowImageFlagDefault";

@interface YZMStockViewController()<YZMSegmentViewDelegate>

@property (nonatomic, strong) YZMSegmentViewFixed *segmentView;
@property (nonatomic, strong) YZMStockEntrustView *entrustView;
@property (nonatomic, strong) YZMStockSellView *sellView;
@property (nonatomic, strong) YZMStockSettlementView *settlementView;
@property (nonatomic, strong) NSString *stockCode;
@property (nonatomic, strong) NSString *stockName;
@property (nonatomic, strong) UIView *hintView;
@property (nonatomic, strong) UILabel *marketValue; //当前市值
@property (nonatomic, strong) UILabel *amountLB;    //可用点买金额
@property (nonatomic, strong) UILabel *textLB;
@property (nonatomic, strong) UIButton *loginBtn;
@property (nonatomic, strong) UILabel *currentLB;
@property (nonatomic, strong) UILabel *usableLB;
@property (nonatomic, strong) YZMMyStackModel *schemeModel;
@property (nonatomic, assign) BOOL unShowErrorFlag;
@property (nonatomic, assign) BOOL unFirstFetchFlag;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, assign) NSInteger currentIndex;
@property (nonatomic, strong) UILabel *bottomLabel;
@property (nonatomic, strong) UIButton *arrowBtn;
@property (nonatomic, strong) UIView *marketView;
@property (nonatomic, strong) UILabel *stopLossTextLB;
@property (nonatomic, strong) UILabel *deferCharge;
@property (nonatomic, strong) UILabel *riskWarningLabel;
@property (nonatomic, strong) YZMConfigureService *service;
@property (nonatomic, strong) YZMMarketValueModel *marketModel;
@property (nonatomic, strong) UIView *noSchemeView;
@property (nonatomic, strong) UIImageView* arrow;

@property (nonatomic, assign) NSInteger scroolIndex_T_1;

@property (nonatomic, assign) NSInteger scroolIndex_T_D;

@property (nonatomic, assign) BOOL isPop;//从上一页面返回

@end

@implementation YZMStockViewController{
    UIImageView *IntroduceImageView;
}

- (id)init{
    
    self = [super init];
    if (self) {
        
        self.tradeType = YZM_TRADE_TYPE_FOR_A_STOCK;
        self.hidesBottomBarWhenPushed = YES;
    }
    
    return self;
}

- (void)viewDidLoad{
    
    [super viewDidLoad];
//    YZMAppDelegate * appDelegate = (YZMAppDelegate *)[UIApplication sharedApplication].delegate;
//    appDelegate.allowRotation = YES;
//    [self setNewOrientation:appDelegate.allowRotation];
    self.segment.selectedSegmentIndex = 0;
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    if (YZMSWitchOn) {
        self.navigationItem.rightBarButtonItem = [YZMAppStyle rightBarItemWithTitle:@"规则" target:self action:@selector(rightBarItemPressed:)];
    }
    [self createObjects];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshScheme) name:@"refreshScheme" object:nil];
  
#ifdef YZMicroStock
    if (![[NSUserDefaults standardUserDefaults]objectForKey:sYZDShowImageFlagDefault]) {
        
//        [self addIntroduce];
       
    }
#endif
}


- (void)addIntroduce{
    
    IntroduceImageView = [UIImageView new];
    [YZMCMInstance.rootTabBarCtrl.view addSubview:IntroduceImageView];
    [IntroduceImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(YZMCMInstance.rootTabBarCtrl.view);
    }];
    [IntroduceImageView setImage:[UIImage imageNamed:@"Image_introduce"]];
    IntroduceImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *dismissTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ImageHiden)];
    [IntroduceImageView addGestureRecognizer:dismissTap];
    
}

-(void)ImageHiden{
    
    IntroduceImageView.hidden = YES;
    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:sYZDShowImageFlagDefault];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    if (self.view.hidden) {
        return;
    }
    if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
        return;
    }
    NSUserDefaults* data = [NSUserDefaults standardUserDefaults];
    if (![self isKindOfClass:[YZMStockTDViewController class]]) {
        
        if (![data objectForKey:@"DMA"]) {
            MTGuideImageView* guide1 = [MTGuideImageView createImage: (iPhoneX ? @"hp2" : (iPhone6P ? @"hp1" : @"hp3"))];
            guide1.block = ^{
                [MTGuideImageView createImage: (iPhoneX ? @"ss2" : (iPhone6P ? @"ss1" : @"ss3"))];
                //                guide2.block = ^{
                //                    [MTGuideImageView createImage: (iPhoneX ? @"dma2" : (iPhone6P ? @"dma1" : @"dma3"))];
                //                };
            };
            [data setObject:@"1" forKey:@"DMA"];
        }
        
    } else {
        
        if (![data objectForKey:@"DMD"]) {
            [MTGuideImageView createImage: (iPhoneX ? @"dmd2" : (iPhone6P ? @"dmd1" : @"dmd3"))];
            [data setObject:@"1" forKey:@"DMD"];
        }
        
    }
    YZMAppDelegate * appDelegate = (YZMAppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotation = NO;
    [self setNewOrientation:appDelegate.allowRotation];
    [self startTimer];
    [self.entrustView updateRedpacket];
//    [self changeTopViewStateWithModel];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyboard:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideKeyboard:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateCurrentIndex:) name:@"UpdateCurrentIndex" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popScroll:) name:PopScrollNSNOtification object:nil];
    if (self.isPop) {
        self.isPop = NO;
        return;
    }
    [self.view layoutIfNeeded];
    [self.segmentView noAnimationAtIndex:self.scroolIndex_T_1];
}


- (void)popScroll:(NSNotification *)noti{
    self.isPop = YES;
}

- (void)updateCurrentIndex:(NSNotification *)noti{
    
    NSInteger currentIndex = [noti.userInfo[@"currentIndex"] integerValue];
    [self.entrustView updateCurrentIndex:currentIndex];
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
//    YZMAppDelegate * appDelegate = (YZMAppDelegate *)[UIApplication sharedApplication].delegate;
//    appDelegate.allowRotation = NO;
//    [self setNewOrientation:appDelegate.allowRotation];
    [self stopTimer];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark -- KeyboardNotification
- (void)showKeyboard:(NSNotification *)noti {
    NSDictionary *dic = noti.userInfo;
    //键盘弹出后的位置
    CGRect endFrame = [dic[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [_segmentView mas_updateConstraints:^(MASConstraintMaker *make){
        
        make.height.mas_equalTo(ScreenHeight - 50 - endFrame.size.height);
    }];
}

- (void)hideKeyboard:(NSNotification *)noti {
    
    [_segmentView mas_updateConstraints:^(MASConstraintMaker *make){
        
        make.height.mas_equalTo(ScreenHeight - 117);
    }];
}

- (void)refreshScheme {
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    [self fecthCurrentSchemeWith:group];
    dispatch_group_enter(group);
    [self fecthStrategyMarketValueWith:group];
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self changeTopViewStateWithModel];
    });
}

- (void)startTimer{
    
    if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_D && YZMUserServiceInstance.currentUser) {
        
        [self refreshScheme];
    }
    
    switch (self.segmentView.currentIndex) {
        case 0:{
            [self.entrustView checkIfNeedRequestConfigureData];
            [self.entrustView startTimer];
            break;
        }
            
        case 1:{
            
            [self.sellView startTimer];
        }
        default:
            break;
    }
    
    [self performSelector:@selector(moveSellOrSettlePage) withObject:nil afterDelay:0.0];
}

- (void)stopTimer{
    
    [self.entrustView stopButtonTimer];
    [self.entrustView stopTimer];
    [self.sellView stopTimer];
}

#pragma mark -- NetWork

- (void)fecthStrategyMarketValueWith:(dispatch_group_t)group {
    
    [YZClient fetchCurrentMarketWithSuccess:^(NSURLSessionDataTask *task, id responseObject) {
        YZGeneralResultModel *topModel=responseObject;
        if (topModel.success) {
            
            self.marketModel = [YZMMarketValueModel mapResponseString:topModel.data];
            
//            if (self.marketModel) {
            
                //有方案
//                [self changeTopViewStateWithModel];
//            }
        }
//        [self changeTopViewStateWithModel];
        
        _unShowErrorFlag = NO;
        dispatch_group_leave(group);
    } failure:^(NSError *error) {
        dispatch_group_leave(group);
//        [self changeTopViewStateWithModel];
        if (!_unShowErrorFlag) {
            
            [error yz_showMessage];
        }
        _unShowErrorFlag = YES;
    }];
}

- (void)fecthCurrentSchemeWith:(dispatch_group_t)group {
    
    if ([self checkNetwork]) {
        dispatch_group_leave(group);
        return;
    }
    
    [YZClient getmystategy:^(NSURLSessionDataTask *task, id responseObject) {
        YZGeneralResultModel *topModel=responseObject;
        if (topModel.success) {
            
            self.schemeModel=topModel.data;
            if (self.schemeModel) {
                //有方案
//                [self changeTopViewStateWithModel];
                self.settlementView.model = self.schemeModel;
                self.entrustView.schemeModel = self.schemeModel;
                self.sellView.schemeModel=self.schemeModel;
                
                BOOL isShow = [[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:@"%@_%@", @(self.schemeModel.Id), @(self.schemeModel.availableDays)]];
                if (self.schemeModel.availableDays <= 2 && !isShow) {
                   
                    YZMAlertView *alertView = [[YZMAlertView alloc] init];
                    alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
                    alertView.contentLabel.text = [NSString stringWithFormat:@"您的策略组还有%@天到期，如需继续合作，请及时申请续期", @(self.schemeModel.availableDays)];
                    [alertView.sureButton setTitle:@"续期" forState:UIControlStateNormal];
                    alertView.confirmHandle = ^(){
                        
                        YZMMYTackViewController *VC = [YZMHCMInstance instanceWithControllerName:@"mytack"];
                        if (VC) {
                            
                            [YZMHCMInstance popViewController];
                        } else {
                            
                            [YZMHCMInstance pushViewControllerWithName:@"mytack" andParams:nil];
                        }
                        
                        return YES;
                    };

                    [alertView showInView:self.navigationController.view];
                    
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:[NSString stringWithFormat:@"%@_%@", @(self.schemeModel.Id), @(self.schemeModel.availableDays)]];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
            }
        }else{
            [MBProgressHUD showMessage:topModel.resultMessage];
        }
        dispatch_group_leave(group);
        
        _unShowErrorFlag = NO;
    } failure:^(NSError *error) {
        dispatch_group_leave(group);
        if (!_unShowErrorFlag) {
            
            [error yz_showMessage];
        }
        _unShowErrorFlag = YES;
    }];
}

#pragma mark -- YZMSegmentViewDelegate

- (void)segmentView:(YZMSegmentView *)segmentView didScrollToIndexView:(NSInteger)index{
    
    NSString *pageName = @"stockTotal";
    switch (self.tradeType) {
        case YZM_TRADE_TYPE_FOR_A_STOCK_D:{
            if ([YZMUserService sharedService].currentUser) {
                self.scroolIndex_T_D = index;
            }
            
        }
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK:{
            if ([YZMUserService sharedService].currentUser) {
                self.scroolIndex_T_1 = index;
            }
            
        }
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_YLB:{
            if ([YZMUserService sharedService].currentUser) {
                self.scroolIndex_T_D = index;
            }
        }
            pageName = @"stockYLB";
            break;
        default:
            break;
    }
    
    if (index == 0) {
        
        [self.entrustView checkIfNeedRequestConfigureData];
        [self.entrustView startTimer];
        [self.sellView stopTimer];
        
        if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_D) {
            
            [self refreshScheme];
            self.sellView.bottomLabel.hidden = YES;
            [self.entrustView updateRedpacket];
        }
        
    }else if(index == 1){

        if (!YZMUserServiceInstance.currentUser) {
            
            __weak __typeof(&*self) weakSelf = self;
            
            [YZMUserService showLoginCtrlWithSourcePageName:pageName andAheadAction:^{
                
                [weakSelf.sellView startTimer];
                [weakSelf.entrustView stopButtonTimer];
                [weakSelf.entrustView stopTimer];
                
            } andBackAction:^{
                
                [weakSelf.segmentView clickAtIndex:0];
            }];
            
            return;
        }
        
        [self.sellView startTimer];
        [self.entrustView stopButtonTimer];
        [self.entrustView stopTimer];
        
        if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_D && YZMUserServiceInstance.currentUser) {
            
            [self refreshScheme];
            self.sellView.bottomLabel.hidden = YES;
        }
        
    }else if(index == 2){

        if (!YZMUserServiceInstance.currentUser) {

            __weak __typeof(&*self) weakSelf = self;

            [YZMUserService showLoginCtrlWithSourcePageName:pageName andAheadAction:^{

                [weakSelf.sellView stopTimer];
                [weakSelf.settlementView fetchSuggestionListFirstPage];
                [weakSelf.entrustView stopButtonTimer];
                [weakSelf.entrustView stopTimer];

            } andBackAction:^{

                [weakSelf.segmentView clickAtIndex:0];
            }];
            return;
        }

        
        [self.sellView stopTimer];
        [self.settlementView fetchSuggestionListFirstPage];
        [self.entrustView stopButtonTimer];
        [self.entrustView stopTimer];
        if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_D && YZMUserServiceInstance.currentUser) {
            
            [self refreshScheme];
            self.sellView.bottomLabel.hidden = YES;
        }
    }
}

#pragma mark -- Event

- (void)showHideView:(UIButton *)send {
    
    WS(ws)
    self.arrowBtn.selected = !self.arrowBtn.selected;
    if (self.arrowBtn.isSelected) {
        self.marketView.hidden = NO;
        [UIView animateWithDuration:0.6 animations:^{
            
            [ws.arrowBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                
                make.left.equalTo(ws.hintView);
            }];
            
            [ws.marketView mas_updateConstraints:^(MASConstraintMaker *make) {
                
                make.top.equalTo(ws.hintView.mas_bottom);
            }];
            
            [ws.segmentView mas_updateConstraints:^(MASConstraintMaker *make){
                
                make.height.mas_equalTo(ScreenHeight - 161);
            }];
            [self.view layoutIfNeeded];
        }];

    } else {
        [UIView animateWithDuration:0.6 animations:^{
            
            [self.arrowBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                
                make.left.equalTo(ws.hintView).offset(-33);
            }];
            
            [self.marketView mas_updateConstraints:^(MASConstraintMaker *make) {
                
                make.top.equalTo(ws.hintView.mas_bottom).offset(-63);
            }];
            
            [ws.segmentView mas_updateConstraints:^(MASConstraintMaker *make){
                
                make.height.mas_equalTo(ScreenHeight - 117);
            }];
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
             self.marketView.hidden = YES;
        }];
    }
}

- (void)moveSellOrSettlePage {
    
    if (self.currentIndex == 1) {
        
        [self showSellListPage];//我的策略组——当前持仓
        self.currentIndex = 0;
    } else if (self.currentIndex == 2) {
        
        [self showSettlementListPage];//我的策略组——交易纪录
        self.currentIndex = 0;
    }
}

- (void)loginMethod:(UIButton *)send {
    
    WS(ws)
    
    if (!YZMUserServiceInstance.currentUser) {
        
        [YZMUserService showLoginCtrlWithSourcePageName:@"stockTD" andAheadAction:^{
            
            [ws.entrustView checkIfNeedRequestConfigureData];
            [ws.entrustView startTimer];
            [ws.sellView stopTimer];
//            [ws changeTopViewStateWithModel];
            [self.entrustView updateRedpacket];
        } andBackAction:^{
            
            [ws.segmentView clickAtIndex:0];
        }];
    } else {
        
        [YZMHCMInstance pushViewControllerWithName:@"stockTDBuy" andParams:nil];
    }
}

- (void)rightBarItemPressed:(id)sender{
    
    [YZMWebViewService openTradeRule:self.tradeType];
}

- (void)showSellListPage{
    
    [self.segmentView clickAtIndex:1];
}

- (void)showEntrustListPage {

    [self.segmentView clickAtIndex:0];
}

- (void)showSettlementListPage {

    [self.segmentView clickAtIndex:2];
}

- (void)mytack {
    [YZMCMInstance pushViewControllerWithName:@"mytack" andParams:@{@"isHidden":@(YES)}];
}

#pragma mark -- Private Method

- (void)setNewOrientation:(BOOL)fullscreen {
    
    if (fullscreen) {
        //不设置方向
        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
        //强制向右横屏
        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
        
    }else{
        //不设置方向
        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
        //强制竖屏
        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
    [self.entrustView endEditing:YES];
}

- (BOOL)checkNetwork {
    
    if (kNetworkNotReachability) {
        
        if (!_unShowErrorFlag) {
            
            [MBProgressHUD showMessage:@"网络无法连接，请联网后重试"];
            _unShowErrorFlag = YES;
        }
        
        return YES;
    }
    
    return NO;
}

- (void)changeTopViewStateWithModel {
    
    if (self.schemeModel) {
        
        self.currentLB.hidden = NO;
        self.usableLB.hidden = NO;
        self.marketValue.hidden = NO;
        self.amountLB.hidden = NO;
        self.textLB.hidden = YES;
        self.loginBtn.hidden = YES;
        self.arrowBtn.hidden = NO;
        self.arrow.hidden = NO;
        self.hintView.backgroundColor = [YZMAppStyle colorForMain];
//        self.noSchemeView.hidden = YES;
        
        self.marketValue.text = @(self.schemeModel.marketValue + self.schemeModel.suspendedValue).p02fString;
        self.amountLB.text = @(self.schemeModel.availableMoney).p02fString;
        double stopLoss = self.schemeModel.money * self.service.defaultConfigure.quitLossRatio / 100;
        self.stopLossTextLB.text = [NSString stringWithFormat:@"到达止损:当前市值+可用余额≤ %@元", @(stopLoss).r2fString];
        
        double deferCharge = (self.schemeModel.money) * self.service.defaultConfigure.deferConditionRatio / 100;
        NSString *detailStr = [NSString stringWithFormat:@"可以递延:当前市值+可用余额≥ %@元(当前%@元)", @(deferCharge).r2fString, @([self.marketModel.schemeMoney doubleValue] + [self.marketModel.availableMoney doubleValue] + [self.marketModel.currentMarkt doubleValue]).r2fString];
        
        NSMutableAttributedString *detailAttStr = [[NSMutableAttributedString alloc] initWithString:detailStr];
        
        NSUInteger len = [detailStr rangeOfString:@")"].location - [detailStr rangeOfString:@"("].location - 4;
        [detailAttStr addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForRiseText] range:NSMakeRange([detailStr rangeOfString:@"("].location + 3,len)];
        
        self.deferCharge.attributedText = detailAttStr;
    } else {
        
        self.currentLB.hidden = YES;
        self.usableLB.hidden = YES;
        self.marketValue.hidden = YES;
        self.amountLB.hidden = YES;
        self.textLB.hidden = NO;
        self.loginBtn.hidden = NO;
        self.arrowBtn.hidden = YES;
//        self.noSchemeView.hidden = NO;
        self.hintView.backgroundColor = [YZMAppStyle colorForString:@"#E2E2E2"];
        if (YZMUserServiceInstance.currentUser) {
            
            self.textLB.text = @"您当前还没有点买策略组，赶紧去申请一个";
        } else {
            
            self.textLB.text = @"您还未登录，立即登录";
        }
    }
}

- (void)createObjects{
    
    WS(ws)
    
    self.scrollView = [[UIScrollView alloc] init];
    CGSize contentSize = CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height - 64);
    if (iPhone4 || iPhone5) {
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.scrollView.showsVerticalScrollIndicator = NO;
        self.scrollView.contentSize = contentSize;
        self.scrollView.bounces = NO;
    }
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(ws.view);
    }];
    
    if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_D) {
        
        UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(mytack)];
        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 1;
        
        self.hintView = [[UIView alloc] init];
        [self.hintView addGestureRecognizer:tap];
        
        [self.scrollView addSubview:self.hintView];
        [self.hintView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.left.right.equalTo(ws.scrollView);
            make.height.mas_equalTo(38);
        }];
        
        _bottomLabel=[YZMAppStyle labelWithSmallWhite];
        _bottomLabel.hidden = YES;
        [self.view addSubview:_bottomLabel];
        _bottomLabel.backgroundColor=[YZMAppStyle colorForLabelMark];
        _bottomLabel.textAlignment=NSTextAlignmentCenter;
        [_bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.right.equalTo(ws.view);
            make.left.equalTo(ws.view);
            make.height.mas_equalTo(36);
        }];
        
        NSString *bottomValue=@"--";
        NSString *bottonString=[NSString stringWithFormat:@"持仓盈亏：%@",bottomValue];
        NSMutableAttributedString *textString=[[NSMutableAttributedString alloc]initWithString:bottonString];
        [textString addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForGrayText] range:NSMakeRange(5, bottomValue.length)];
        _bottomLabel.attributedText=textString;
        
        UIFont *fontSize = [YZMAppStyle smallSizeFont];
        if (iPhone4 || iPhone5) {
            
            fontSize = [YZMAppStyle fontWithSize:10];
        }
        
        UIView *lineView = [YZMAppStyle splitLine];
        [self.hintView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.left.right.equalTo(ws.hintView);
        }];
        
        self.currentLB = [YZMAppStyle labelWithSmallWhite];
        self.currentLB.hidden = YES;
        self.currentLB.text = @"当前市值:";
        self.currentLB.font = fontSize;
        [self.hintView addSubview:self.currentLB];
        [self.currentLB mas_makeConstraints:^(MASConstraintMaker *make) {
            
            if (iPhone4 || iPhone5 || !(iPhone6 || iPhone6P || iPhoneX)) {
                
                make.left.equalTo(ws.hintView).offset(10);
            } else {
                
                make.left.equalTo(ws.hintView).offset(30);
            }
            make.centerY.equalTo(ws.hintView);
            make.width.mas_equalTo(58);
        }];
        
        self.marketValue = [YZMAppStyle labelWithSmallYellow];
        self.marketValue.hidden = YES;
        self.marketValue.font = fontSize;
        self.marketValue.text = @"--";
        self.marketValue.adjustsFontSizeToFitWidth = YES;
        self.marketValue.minimumScaleFactor = 0.1;
        [self.hintView addSubview:self.marketValue];
        [self.marketValue mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(ws.currentLB.mas_right);
            make.right.equalTo(ws.hintView.mas_centerX);
            make.centerY.equalTo(ws.hintView);
        }];
        
        self.usableLB = [YZMAppStyle labelWithSmallWhite];
        self.usableLB.hidden = YES;
        self.usableLB.font = fontSize;
        self.usableLB.text = @"可用点买金额:";
        [self.hintView addSubview:self.usableLB];
        [self.usableLB mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(ws.hintView.mas_centerX).offset(5);
            make.centerY.equalTo(ws.marketValue);
            make.width.mas_equalTo(83);
        }];
        
        self.amountLB = [YZMAppStyle labelWithSmallYellow];
        self.amountLB.hidden = YES;
        self.amountLB.font = fontSize;
        self.amountLB.text = @"--";
        self.amountLB.adjustsFontSizeToFitWidth = YES;
        self.amountLB.minimumScaleFactor = 0.1;
        [self.hintView addSubview:self.amountLB];
        [self.amountLB mas_makeConstraints:^(MASConstraintMaker *make) {
            
            if (iPhone4 || iPhone5 || !(iPhone6 || iPhone6P || iPhoneX)) {
                
                make.right.equalTo(ws.hintView).offset(-10);
            } else {
                
                make.right.equalTo(ws.hintView).offset(-20);
            }
            make.left.equalTo(ws.usableLB.mas_right);
            make.centerY.equalTo(ws.marketValue);
        }];
        
        //图标
        _arrow = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"historyarrow"]];
        _arrow.hidden = YES;
        _arrow.contentMode = UIViewContentModeScaleAspectFit;
        [self.hintView addSubview:_arrow];
        
        [_arrow mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.hintView).offset(-15);
            make.centerY.equalTo(self.amountLB);
            make.top.equalTo(self.hintView).offset(5);
            make.bottom.equalTo(self.hintView).offset(-5);
            make.width.mas_equalTo(10);
        }];

        self.textLB = [YZMAppStyle labelWithMediumGray];
        self.textLB.hidden = YES;
        self.textLB.textAlignment = NSTextAlignmentCenter;
        self.textLB.adjustsFontSizeToFitWidth = YES;
        [self.hintView addSubview:self.textLB];
        [self.textLB mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(ws.hintView).offset(32);
            make.right.equalTo(ws.hintView).offset(-32);
            make.centerY.equalTo(ws.hintView);
        }];
        
        self.loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.loginBtn.hidden = YES;
//        self.loginBtn.backgroundColor = [UIColor redColor];
        [self.loginBtn setImage:[UIImage imageNamed:@"icon_gray_right_arrow"] forState:UIControlStateNormal];
        self.loginBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -ScreenWidth + 45);
        [self.hintView addSubview:self.loginBtn];
        [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.bottom.left.right.equalTo(ws.hintView);
            make.centerY.equalTo(ws.hintView);
        }];
        [self.loginBtn addTarget:self action:@selector(loginMethod:) forControlEvents:UIControlEventTouchUpInside];
        
        self.arrowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.arrowBtn.hidden = YES;
        self.arrowBtn.selected = NO;
        [self.arrowBtn setImage:[UIImage imageNamed:@"icon_left_arrow"] forState:UIControlStateNormal];
//        self.arrowBtn.backgroundColor = [UIColor blueColor];
        [self.arrowBtn addTarget:self action:@selector(showHideView:) forControlEvents:UIControlEventTouchUpInside];
        [self.hintView addSubview:self.arrowBtn];
        [self.arrowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(ws.hintView).offset(-33);
            make.centerY.equalTo(ws.hintView);
            make.height.mas_equalTo(38);
        }];
        
        self.marketView = [[UIView alloc] init];
        self.marketView.backgroundColor = [YZMAppStyle colorForString:@"#E2E2E2"];
        [self.scrollView insertSubview:self.marketView belowSubview:self.hintView];
        [self.marketView mas_makeConstraints:^(MASConstraintMaker *make) {
    
            if (iPhoneX) {
                
            } make.top.equalTo(ws.hintView.mas_bottom).with.offset(-63);
            make.left.right.equalTo(ws.scrollView);
            make.height.mas_equalTo(63);
        }];
        self.marketView.hidden = YES;
        
        self.stopLossTextLB = [YZMAppStyle labelWithSmallGray];
        self.stopLossTextLB.text = @"--";
        if (iPhone4 || iPhone5 || !(iPhone6 || iPhone6P || iPhoneX)) {
            
            self.stopLossTextLB.font = [YZMAppStyle fontWithSize:10];
        }
        [self.marketView addSubview:self.stopLossTextLB];
        [self.stopLossTextLB mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(ws.marketView).offset(5);
            make.top.equalTo(ws.marketView).offset(9);
        }];
        
        self.deferCharge = [YZMAppStyle labelWithSmallGray];
        self.deferCharge.text = @"可以递延:当前市值+可用余额≥ 15000元(当前10000元)";
        if (iPhone4 || iPhone5 || !(iPhone6 || iPhone6P || iPhoneX)) {
            
            self.deferCharge.font = [YZMAppStyle fontWithSize:10];
        }
        [self.marketView addSubview:self.deferCharge];
        [self.deferCharge mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(ws.marketView).offset(5);
            make.top.equalTo(ws.stopLossTextLB.mas_bottom).offset(1);
        }];
        
        self.riskWarningLabel = [YZMAppStyle labelWithSmallGray];
        self.riskWarningLabel.textColor = [YZMAppStyle colorForRiseText];
        self.riskWarningLabel.text = @"注：风险股无法递延";
        if (iPhone4 || iPhone5 || !(iPhone6 || iPhone6P || iPhoneX)) {
            
            self.riskWarningLabel.font = [YZMAppStyle fontWithSize:10];
        }
        [self.marketView addSubview:self.riskWarningLabel];
        [self.riskWarningLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(ws.marketView).offset(5);
        make.top.equalTo(ws.deferCharge.mas_bottom).offset(1);
        }];
        
//        self.noSchemeView = [UIView new];
//        self.noSchemeView.backgroundColor = [YZMAppStyle appBackgroundColor];
//        self.noSchemeView.alpha = 0.75;
//        [self.view addSubview:self.noSchemeView];
//
//        [self.noSchemeView mas_makeConstraints:^(MASConstraintMaker *make) {
//
//            make.height.mas_equalTo(ScreenHeight-38);
//            make.left.right.equalTo(ws.view);
//            make.top.equalTo(ws.hintView.mas_bottom);
//        }];
        
//        [self changeTopViewStateWithModel];
    }
    
    self.segmentView = [YZMSegmentViewFixed new];
    [self.scrollView addSubview:self.segmentView];

    [_segmentView mas_makeConstraints:^(MASConstraintMaker *make){
        
        if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_D) {
            
            make.top.equalTo(ws.marketView.mas_bottom).offset(14);
            make.height.mas_equalTo(ScreenHeight - 117);
        } else {
            
            make.top.equalTo(ws.view).offset(14);
            make.height.mas_equalTo(ScreenHeight - 78);
        }
        make.bottom.left.right.equalTo(ws.scrollView);
        make.width.equalTo(ws.view);
    }];
    
    self.sellView = [[YZMStockSellView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain andTradeType:self.tradeType];
    if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_D) {
        
        self.sellView.bottomLabel = _bottomLabel;
    }
    self.settlementView = [[YZMStockSettlementView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain andTradeType:self.tradeType];
    self.entrustView = [[YZMStockEntrustView alloc] initWithFrame:self.view.frame andTradeType:self.tradeType];

    self.segmentView.delegate = self;
    self.segmentView.titleArray = @[@"点买", @"点卖", @"结算"];
    self.segmentView.viewArray = @[self.entrustView, self.sellView, self.settlementView];

    if (self.stockCode) {
        
        [self.entrustView updateWithStockCode:self.stockCode andStockName:self.stockName];
    }
    
}

//- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    [self.segmentView clickAtIndex:self.scroolIndex];
//}

#pragma mark - controller manager support

- (void)updateWithParamsManual: (NSDictionary *)params{
    
    [self updateWithParams:params];
    if (self.stockCode) {
        
        [self.entrustView updateWithStockCode:self.stockCode andStockName:self.stockName];
    }
}

#define sYZMTradeSaveStockName @"YZMTradeSaveStockName"
#define sYZMTradeSaveStockCode @"YZMTradeSaveStockCode"

- (void)updateWithParams: (NSDictionary *)params
{
    self.tradeType = YZM_TRADE_TYPE_FOR_A_STOCK;
    self.service = [YZMConfigureService sharedServiceWithTradeType:YZM_TRADE_TYPE_FOR_A_STOCK];
    self.stockName = params[@"stockname"];
    self.stockCode  = params[@"stockcode"];
    self.scroolIndex_T_1 = [params[scrollIndexTOne] integerValue];
    self.scroolIndex_T_D = [params[scrollIndexTD] integerValue];
    if (self.stockCode.length == 0) {
        
        NSString *savedCode = [[NSUserDefaults standardUserDefaults] objectForKey: sYZMTradeSaveStockCode];
        NSString *savedName = [[NSUserDefaults standardUserDefaults] objectForKey: sYZMTradeSaveStockName];
        
        if (savedCode.length == 0) {
            
            self.stockCode = @"SH601318";
            self.stockName = @"中国平安";
        }else{
            
            self.stockCode = savedCode;
            self.stockName = savedName;
        }
    }
    
    if (self.stockCode.length != 0) {
        
        [[NSUserDefaults standardUserDefaults] setObject: self.stockCode forKey: sYZMTradeSaveStockCode];
        [[NSUserDefaults standardUserDefaults] setObject: self.stockName forKey: sYZMTradeSaveStockName];
    }
}

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMStockViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

- (void)setTradeType:(YZM_TRADE_TYPE)tradeType{
    
    [super setTradeType:tradeType];
}

- (void)showTradeViewWithType:(YZM_TRADE_TYPE)type{
    
    switch (type) {
        case YZM_TRADE_TYPE_FOR_A_STOCK:
            
            [YZMHCMInstance setAfterRootWithName:@"stock" andParams:@{scrollIndexTOne:@(self.scroolIndex_T_1),scrollIndexTD:@(self.scroolIndex_T_D)} atIndex:self.tabBarController.selectedIndex];
            
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_D:
            
            [YZMHCMInstance setAfterRootWithName:@"stockTD" andParams:@{scrollIndexTOne:@(self.scroolIndex_T_1) ,scrollIndexTD:@(self.scroolIndex_T_D)} atIndex:self.tabBarController.selectedIndex];
            
            break;
            case YZM_TRADE_TYPE_FOR_A_STOCK_ONE:
            case YZM_TRADE_TYPE_FOR_A_STOCK_SIM:
            case YZM_TRADE_TYPE_FOR_A_STOCK_FREE:
            case YZM_TRADE_TYPE_FOR_A_STOCK_YLB:
            break;
    }
}

@end

@interface YZMStockTDViewController ()

@property (nonatomic, assign) BOOL isPopForD;

@end

@implementation YZMStockTDViewController

#define sYZMTradeSaveTDStockName @"YZMTradeSaveTDStockName"
#define sYZMTradeSaveTDStockCode @"YZMTradeSaveTDStockCode"

- (void)viewDidLoad{
    [super viewDidLoad];
//    self.segment.selectedSegmentIndex = 1;
}

- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
    if (self.view.hidden) {
        return;
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popScroll:) name:PopScrollNSNOtification object:nil];
    if (self.isPopForD) {
        self.isPopForD = NO;
        return;
    }
    [self.view layoutIfNeeded];
    if (self.currentIndex > 0) {
        [self.segmentView noAnimationAtIndex:self.currentIndex];
    }else{
        [self.segmentView noAnimationAtIndex:self.scroolIndex_T_D];
    }
}

- (void)popScroll:(NSNotification *)noti{
    self.isPop = YES;
    self.isPopForD = YES;
}

- (void)updateWithParams: (NSDictionary *)params
{
    self.tradeType = YZM_TRADE_TYPE_FOR_A_STOCK_D;
    self.service = [YZMConfigureService sharedServiceWithTradeType:YZM_TRADE_TYPE_FOR_A_STOCK_D];
    NSDictionary *param = [params copy];
    self.stockName = param[@"stockname"];
    self.stockCode  = param[@"stockcode"];
    self.currentIndex = [param[@"segment"] integerValue];
    self.scroolIndex_T_1 = [[param objectForKey:scrollIndexTOne] integerValue];
    self.scroolIndex_T_D = [[param objectForKey:scrollIndexTD] integerValue];
    if (self.stockCode.length == 0) {
        
        NSString *savedCode = [[NSUserDefaults standardUserDefaults] objectForKey: sYZMTradeSaveStockCode];
        NSString *savedName = [[NSUserDefaults standardUserDefaults] objectForKey: sYZMTradeSaveStockName];
        
        if (savedCode.length == 0) {
            
            self.stockCode = @"SH601318";
            self.stockName = @"中国平安";
        }else{
            
            self.stockCode = savedCode;
            self.stockName = savedName;
        }
    }
    
    if (self.stockCode.length != 0) {
        
        [[NSUserDefaults standardUserDefaults] setObject: self.stockCode forKey: sYZMTradeSaveStockCode];
        [[NSUserDefaults standardUserDefaults] setObject: self.stockName forKey: sYZMTradeSaveStockName];
    }
    
    if (!self.currentIndex) {
        
        self.currentIndex = 0;
    }
}

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMStockTDViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

@end

@interface YZMStockYLBViewController ()

@property (nonatomic, assign) BOOL isPopForYLB;

@property (nonatomic, strong) UILabel* labelTitle;

@end

@implementation YZMStockYLBViewController

- (void)updateWithParams: (NSDictionary *)params
{
    self.tradeType = YZM_TRADE_TYPE_FOR_A_STOCK_YLB;
    self.service = [YZMConfigureService sharedServiceWithTradeType:YZM_TRADE_TYPE_FOR_A_STOCK_YLB];
    NSDictionary *param = [params copy];
    self.stockName = param[@"stockname"];
    self.stockCode  = param[@"stockcode"];
    self.currentIndex = [param[@"segment"] integerValue];
//    self.scroolIndex_T_1 = [[param objectForKey:scrollIndexTOne] integerValue];
//    self.scroolIndex_T_D = [[param objectForKey:scrollIndexTD] integerValue];
    if (self.stockCode.length == 0) {
        
        NSString *savedCode = [[NSUserDefaults standardUserDefaults] objectForKey: sYZMTradeSaveStockCode];
        NSString *savedName = [[NSUserDefaults standardUserDefaults] objectForKey: sYZMTradeSaveStockName];
        
        if (savedCode.length == 0) {
            
            self.stockCode = @"SH601318";
            self.stockName = @"中国平安";
        }else{
            
            self.stockCode = savedCode;
            self.stockName = savedName;
        }
    }
    
    if (self.stockCode.length != 0) {
        
        [[NSUserDefaults standardUserDefaults] setObject: self.stockCode forKey: sYZMTradeSaveStockCode];
        [[NSUserDefaults standardUserDefaults] setObject: self.stockName forKey: sYZMTradeSaveStockName];
    }
    
    if (!self.currentIndex) {
        
        self.currentIndex = 0;
    }
}

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMStockYLBViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationItem.titleView = self.labelTitle;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popScroll:) name:PopScrollNSNOtification object:nil];
    if (self.isPopForYLB) {
        self.isPopForYLB = NO;
        return;
    }
    [self.view layoutIfNeeded];
    [self.segmentView noAnimationAtIndex:self.scroolIndex_T_D];
}

- (void)popScroll:(NSNotification *)noti{
    self.isPop = YES;
    self.isPopForYLB = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.segment = nil;
    [self createView];
}

- (void)createView {
    _labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 64, 32)];
    _labelTitle.text = @"盈利宝";
    _labelTitle.textColor = [UIColor whiteColor];
    _labelTitle.textAlignment = NSTextAlignmentCenter;
}



@end
